<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <title>Beehive - 个人中心</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
    <link rel="stylesheet" th:href="@{/css/beeui.css}">
    <link rel="stylesheet" th:href="@{/beehive/css/main.css}">
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <!-- jq要放在layui.js前（依赖）-->
    <script th:src="@{/js/jquery-3.4.0.js}"></script>
    <script th:src="@{/layui/layui.js}"></script>

    <style>
        a:hover {
            text-decoration: none;
        }

    </style>

</head>

<body>

<!-- 引用公共头部 -->
<header th:replace="common :: header"></header>

<!-- 导航条 -->
<nav th:replace="common :: commonNav"></nav>


<div id="app" class="container-fluid" style="background-color: #f5f6fa; padding: 50px 0 20px 0">
    <div style="width: 1100px; margin: 0 auto; background-color: #ffffff; border-radius: 10px">
        <div style="font-size: 18px; padding-top: 20px; padding-left: 20px">个人中心</div>
        <hr style="background-color: #f5f6fa">
        <span class="layui-breadcrumb" lay-separator="|" style="margin-left: 20px">
          <a href="#" v-on:click.prevent="comName='info'">信息资料</a>
          <a href="#" v-on:click.prevent="comName='profile'">修改头像</a>
          <a href="#" v-on:click.prevent="comName='name'">修改用户名</a>
          <a href="#" v-on:click.prevent="comName='email'">修改邮箱</a>
          <a href="#" v-on:click.prevent="comName='pass'">修改密码</a>
        </span>
        <component v-bind:is="comName"></component>





    </div>
</div>

<footer th:replace="common :: commonFooter"></footer>


<script th:src="@{/js/vue.js}"></script>


<script th:inline="javascript">


    // 个人信息组件
    Vue.component('info', {
        template: '              <div class="row" style="margin-top: 50px; margin-bottom: 50px; padding-bottom: 100px">\n' +
            '                        <div class="col-2" style="margin-left: 20px">\n' +
            '                            <img id="headImg" \n' +
            '                                 class="rounded" style="width: 100px; height: 100px;">\n' +
            '                        </div>\n' +
            '                        <div class="col-10" style="margin-left: -60px">\n' +
            '                            <div class="row" style="margin-bottom: 20px;">\n' +
            '                                <div class="col-2">\n' +
            '                                    <span style="color: #3490de">用户名：[[${session.loginUser.username}]]</span>\n' +
            '                                </div>\n' +
            '                                <div class="col">\n' +
            '                                    <span style="">邮&emsp;箱：[[${session.loginUser.email}]]</span>\n' +
            '                                </div>\n' +
            '                            </div>\n' +
            '                            <div class="row" style="margin-bottom: 20px;">\n' +
            '                                <div class="col-2">\n' +
            '                                    <span>姓&emsp;名：[[${session.loginUser.realName}]]</span>\n' +
            '                                </div>\n' +
            '                                <div class="col">\n' +
            '                                    <span style="">手机号码：[[${session.loginUser.phoneNum}]]</span>\n' +
            '                                </div>\n' +
            '                            </div>\n' +
            '                            <div class="row">\n' +
            '                                <div class="col-2">\n' +
            '                                    <span>性&emsp;别：[[${session.loginUser.gender == 0 ? '女' : '男'}]]&emsp;</span>\n' +
            '                                </div>\n' +
            '                                <div class="col">\n' +
            '                                    <span style="">注册时间：[[${#dates.format(session.loginUser.registerTime, 'yyyy-MM-dd HH:mm:ss')}]]</span>\n' +
            '                                </div>\n' +
            '                            </div>\n' +
            '                        </div>\n' +
            '                    </div>\n'
    })

    // 修改头像组件
    Vue.component('profile', {
        template: '  <div>\n' +
            '            <div class="col-7" style="margin-left: 20px; font-size: 14px; width: 580px; padding-left: 0; border-left: 5px solid #f64662; margin-top: 10px; color: #999999">\n' +
            '                <span>请选择您要修改的头像</span>\n' +
            '            </div>\n' +
            '            <div class="row">\n' +
            '                <div id="headImgList" class="col-7" style="margin-left: 20px; padding-top: 20px; padding-bottom: 10px">\n' +
            '                </div>\n' +
            '                <div class="col" style="margin-left: 20px; padding-top: 20px; padding-bottom: 20px">\n' +
            '                    <div class="row" style="margin-left: 30px"><img id="oriProfile" width="150px" height="150px" class="rounded"></div>\n' +
            '                    <div class="row" style="margin: 20px 30px"><button class="btn btn-primary" style="width: 150px" onclick="toModifyProfile()">确定</button></div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>'
    })


    // 修改用户组件
    Vue.component('name', {
        template: '    <div>\n' +
            '            <div class="layui-form-item" style="margin-top: 20px">\n' +
            '                <label class="layui-form-label">用户名</label>\n' +
            '                <div class="layui-input-block">\n' +
            '                    <input type="text" name="username" id="username" required\n' +
            '                           class="layui-input" style="width: 200px">\n' +
            '                </div>\n' +
            '            </div>\n' +
            '            <div class="layui-form-item" style="margin-bottom: 40px; padding-bottom: 40px">\n' +
            '                <div class="layui-input-block">\n' +
            '                    <button class="layui-btn layui-btn-normal" onclick="toUpdateUserName()">提交</button>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>'
    })


    Vue.component('email', {
        template: '    <div>\n' +
            '            <div class="layui-form-item" style="margin-top: 20px">\n' +
            '                <label class="layui-form-label">邮箱</label>\n' +
            '                <div class="layui-input-block">\n' +
            '                    <input type="text" name="username" id="email" required lay-verify="email"\n' +
            '                           class="layui-input" style="width: 200px">\n' +
            '                </div>\n' +
            '            </div>\n' +
            '            <div class="layui-form-item" style="margin-bottom: 40px; padding-bottom: 40px">\n' +
            '                <div class="layui-input-block">\n' +
            '                    <button class="layui-btn layui-btn-normal" onclick="toUpdateEmail()">提交</button>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>'
    })

    Vue.component('pass', {
        template: '<div>\n' +
            '            <div class="layui-form">\n' +
            '                <div class="layui-form-item" style="margin-top: 20px; margin-bottom: 6px">\n' +
            '                    <label class="layui-form-label" style="width: 100px;">当前密码</label>\n' +
            '                    <div class="layui-input-block">\n' +
            '                        <input type="password" name="password" required lay-verify="required" placeholder="请输入原密码" class="layui-input" style="width: 220px">\n' +
            '                    </div>\n' +
            '                    <span id="tip1" style="color: red; margin-left: 10px"></span>\n' +
            '                </div>\n' +
            '                <div class="layui-form-item" style="margin-bottom: 6px">\n' +
            '                    <label class="layui-form-label" style="width: 100px;">新密码</label>\n' +
            '                    <div class="layui-input-block">\n' +
            '                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" class="layui-input" style="width: 220px">\n' +
            '                    </div>\n' +
            '                    <span id="tip2" style="color: red; margin-left: 10px"></span>\n' +
            '                </div>\n' +
            '                <div class="layui-form-item" style="margin-bottom: 6px">\n' +
            '                    <label class="layui-form-label" style="width: 100px;">确认密码</label>\n' +
            '                    <div class="layui-input-block">\n' +
            '                        <input type="password" name="password" required lay-verify="required" placeholder="请输入确认密码" class="layui-input" style="width: 220px">\n' +
            '                    </div>\n' +
            '                    <span id="tip3" style="color: red; margin-left: 10px"></span>\n' +
            '                </div>\n' +
            '                <div class="layui-form-item">\n' +
            '                    <div class="layui-input-block" style="margin-bottom: 25px; padding-bottom: 25px">\n' +
            '                        <button class="layui-btn" lay-submit onclick="toUpdatePassword()">提交</button>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>'
    })

    // 个人中心需要注意新注册用户没有头像
    //<![CDATA[
    let vm = new Vue({
        el: '#app',
        data: {
            comName: 'info',
            path: [[${session.loginUser.src != null ? #strings.replace(session.loginUser.src, 'd:/bms/book', 'path') : ''}]],
            username: [[${session.loginUser.username}]],
            email: [[${session.loginUser.email}]]
        },
        // 使用钩子函数解决切换组件时头像不显示的问题
        updated() {
            if (this.comName === "info") {
                if (this.path.length !== 0) {
                    $("#headImg").attr("src", "../" + vm.path);
                } else {
                    $("#headImg").attr("src", "/img/logo_lg.png")
                }
                return;
            }
            if (this.comName === "profile") {
                getProfileList();
                if (this.path.length !== 0) {
                    $("#oriProfile").attr("src", "../" + vm.path);
                } else {
                    $("#oriProfile").attr("src", "/img/logo_lg.png")
                }
                return;
            }
            if (this.comName === 'name') {
                $("#username").val(vm.username);
                return;
            }
            if (this.comName === 'email') {
                $("#email").val(vm.email);
            }
        }
    });
    //]]>

    // 解决初始化页面时不显示头像的问题
    $(function () {
        console.log("页面初始化时执行！");
        if (vm.path.length !== 0) {
            $("#headImg").attr("src", "../" + vm.path);
        } else {
            $("#headImg").attr("src", "/img/logo_lg.png")
        }
        console.log("页面初始执行结束！");
    });

    // 使用layui的水平导航
    layui.use(['form', 'element', 'layer'], function(){
        let element = layui.element;
        let layer = layui.layer;
        let form = layui.form;
    });

    // 获取头像列表
    function getProfileList() {
        // 删除子元素
        $("#headImgList").empty();
        $.get('/user/getProfile').done(function (data) {
            // JSON 字符串一定要解析成JSON对象！！！
            data = JSON.parse(data);
            for (let row in data) {
                let id = data[row].id;
                let src = data[row].src.replace("d:/bms/book/", "/path/");
                $("#headImgList").append(
                    "<img id='"+  id + "' src='" + src + "'" +
                    "     width=\"100px\" height=\"100px\" " + " onclick='clickProfile("+ id + ")'" +
                    "     class=\"rounded\" style='margin-right: 20px; margin-bottom: 20px'>"
                )
            }
        });
    }


    // 保存用户选中头像的ID
    let newProfileId;


    // 监听头像列表
    function clickProfile(imgId) {
        // 选中一个头像，清除之前选中的状态（有缺陷，因为第一次选中，没有上一次）
        $("#"+newProfileId).css("box-shadow", "");
        // attr方法可以获取属性值
        let profile = $("#" + imgId);
        // 获取选中头像的资源路径
        let src = profile.attr("src");
        // 设置样式高亮显示被选中状态
        profile.css("box-shadow", "1px 1px 10px 6px #f38181");
        // 保存选中的头像ID
        newProfileId = imgId;
        // 显示新头像
        $("#oriProfile").attr("src", src);
    }

    // 修改头像
    function toModifyProfile() {
        let userId = [[${session.loginUser.id}]]
        $.ajax({
            url: '/user/updateProfile',
            type: 'post',
            data: JSON.stringify({userId: userId, headImgId: newProfileId}),
            contentType: 'application/json;charset=utf-8',
            success: function (result) {
                if (result !== 0) {
                    layer.open({title: '提示', icon: 1, content: '修改头像成功！', shadeClose: true, time: 1800});
                    // 因为layer是异步执行，设置定时器刷新页面，重新请求
                    setTimeout(function () {
                        location.reload();
                    }, 1800);
                } else {
                    layer.open({title: '提示', icon: 2, content: '修改头像失败，请稍后再试！', shadeClose: true, time: 1800});
                }
            }, error: function () {
                layer.open({title: '提示', icon: 0, content: 'Beehive开小差去啦！', shadeClose: true, time: 1800});
            }
        })
    }


    // 修改用户名
    function toUpdateUserName() {
        vm.username = $("#username").val();
        if (vm.username.length === 0) {
            layer.msg('用户名不允许为空！', {icon: 0, anim: 6});
        }
        $.ajax({
            url: '/user/updateUserName',
            type: 'post',
            data: JSON.stringify({id: [[${session.loginUser.id}]], username: vm.username}),
            contentType: 'application/json;charsrt=utf-8',
            success: function (flag) {
                if (flag <= 0) {
                    layer.open({title: '提示', icon: 0, content: '这个用户名太抢手啦，换一个吧', shadeClose: true, time: 1800});
                    return ;
                }
                if (flag !== 0) {
                    layer.open({title: '提示', icon: 1, content: '修改用户名成功！', shadeClose: true, time: 1800});
                    setTimeout(function () {
                        location.reload();
                    }, 1800);
                } else {
                    layer.open({title: '提示', icon: 0, content: '服务器繁忙，请稍后再试！', shadeClose: true, time: 1800});
                }
            }, error: function () {
                layer.open({title: '提示', icon: 2, content: '服务器内部错误！', shadeClose: true, time: 1800});
            }
        })
    }

    // 修改邮箱
    function toUpdateEmail() {
        vm.email = $("#email").val();
        if (vm.email.length === 0) {
            layer.msg('邮箱不允许为空！', {icon: 0, anim: 6});
        } else {
            let reg=/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
            flag = reg.test(vm.email);
            if (flag === false) {
                layer.open({title: '警告', icon:2, content: '邮箱格式不正确！', shadeClose: true, time: 1800});
                return;
            }
        }

        $.ajax({
            url: '/user/updateEmail',
            type: 'post',
            data: JSON.stringify({id: [[${session.loginUser.id}]], email: vm.email}),
            contentType: 'application/json;charset=utf-8',
            success: function (flag) {
                console.log("返回值flag:" + flag)
                if (flag <= 0) {
                    layer.open({title: '提示', icon: 0, content: '该邮箱已被使用，请换一个吧。', shadeClose: true, time: 1800});
                    return ;
                }
                if (flag !== 0) {
                    layer.open({title: '提示', icon: 1, content: '修改邮箱成功！', shadeClose: true, time: 1800});
                    setTimeout(function () {
                        location.reload();
                    }, 1800);
                } else {
                    layer.open({title: '提示', icon: 0, content: '服务器繁忙，请稍后再试！', shadeClose: true, time: 1800});
                }
            }, error: function () {
                layer.open({title: '提示', icon: 2, content: '服务器内部错误！', shadeClose: true, time: 1800});
            }
        });
    }


    // 修改密码
    function toUpdatePassword() {
        // 1、先查询原密码是否正确
        let pass = document.getElementsByName("password");
        if(pass[0].value.length === 0 || pass[1].value.length === 0 || pass[2].value.length === 0) {
            return;
        }

        $.ajax({
            url: '/user/verifyPassword',
            type: 'post',
            data: JSON.stringify({id: [[${session.loginUser.id}]], password: pass[0].value}),
            contentType: 'application/json;charset=utf-8',
            success: function (flag) {
                console.log("与原密码对比结果：" + flag)
                let tip1 = $("#tip1");
                if (flag === String(0)) {
                    tip1.html("密码错误！");
                } else {
                    tip1.css("color", "green");
                    tip1.html("密码正确！");
                }
            }
        });
        let pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z]).{8,30}');
        let tip2 = $("#tip2");
        if (!pwdRegex.test(pass[1].value)) {
            tip2.html("您的密码复杂度太低（密码中必须包含字母、数字，8-30位）！");
            return;
        } else {
            tip2.html("您的密码复杂度一般");
            tip2.css("color", "green");
        }
        let tip3 = $("#tip3");
        if (pass[1].value !== pass[2].value) {
            tip3.html("两次密码不相等！");
            return;
        } else {
            tip3.html("密码一致");
            tip3.css("color", "green");
        }
        // 2、校验新密码强度并对比新密码与确认密码
        $.ajax({
            url: '/user/updatePassword',
            type: 'post',
            data: JSON.stringify({id: [[${session.loginUser.id}]], password: pass[2].value}),
            contentType: 'application/json;charset=utf-8',
            success: function (flag) {
                console.log("修改密码回调函数，flag的值是：" + flag)
                if (flag !== 0) {
                    layer.open({title: '提示', icon: 1, content: '密码修改成功！', time: 1800, shadeClose: true});
                    setTimeout(function (){
                        // location.reload();
                    }, 1800)
                } else {
                    layer.open({title: '提示', icon: 0, content: '密码修改失败！', time: 1800, shadeClose: true});
                }
            },
            error: function () {
                layer.open({title: '提示', icon: 2, content: '服务器错误！', time: 1800, shadeClose: true});
            }
        });
    }

</script>

</body>
</html>
